package com.qm.console.component.thirdapi.qiniu;

import com.qiniu.cdn.CdnManager;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qm.console.component.thirdapi.qiniu.config.UploadConfig;
import com.qm.console.component.thirdapi.qiniu.config.UploadConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.ArrayList;
import java.util.List;




public class QiniuClient {

    private static Logger LOG = LoggerFactory.getLogger(QiniuClient.class);

    public static UploadToken getUploadToken(String type, String fileKey) {
        Auth auth = Auth.create(UploadConfig.getAccessKey(), UploadConfig.getSecretKey());
        if (fileKey != null){
            fileKey = getTypeMap(type) + "/" + fileKey;
        }
        String token = auth.uploadToken(UploadConfig.getBucket(), fileKey, UploadConfig.getExpireInterval(), null);
        UploadToken uploadToken = new UploadToken(token, fileKey);
        return uploadToken;
    }

    public static String uploadRemoteFile(String type, MultipartFile file, String fileKey) {
        UploadToken uploadToken = getUploadToken(type, fileKey);
        try {
            Response res = uploadManager().put(file.getInputStream(), uploadToken.getFileKey(), uploadToken.getToken(), null, null);
            LOG.info("qiniu upload res <{}>", res.bodyString());
        } catch (QiniuException ex) {
            ex.printStackTrace();
            Response r = ex.response;
            LOG.info("qiniu excetipon <{}>", r.toString());
            return null;

        } catch (IOException e) {
            e.printStackTrace();
            LOG.info("upload remote file error url: " + file.getName());
            return null;
        }

        return uploadToken.getFileKey();
    }

    private static File copyToTmpFile(InputStream from)
    {
        FileOutputStream os = null;
        try
        {
            File to = File.createTempFile("qiniu_", ".tmp");
            os = new FileOutputStream(to);
            byte[] b = new byte[64 * 1024];
            int l;
            while ((l = from.read(b)) != -1)
            {
                os.write(b, 0, l);
            }
            os.flush();
            return to;
        }
        catch (Exception e)
        {
            throw new RuntimeException("create tmp file failed.", e);
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (Exception e)
                {
                }
            }
            if (from != null)
            {
                try
                {
                    from.close();
                }
                catch (Exception e)
                {
                }
            }
        }
    }

    public static String getTypeMap(String type) {
        String bucketName = null;
        switch (type) {
            case "image":
                bucketName = UploadConfig.getImage();
                break;
            case "video":
                bucketName = UploadConfig.getVideo();
                break;
            case "file":
                bucketName = UploadConfig.getFile();
                break;
        }
        return bucketName;
    }

    private static final UploadManager uploadManager() {
        return UploadManagerHolder.instance;
    }

    private static class UploadManagerHolder {
        private static final UploadManager instance = uploadManager();
        private static UploadManager uploadManager() {
            Zone z = Zone.autoZone();
            Configuration c = new Configuration(z);
            UploadManager uploadManager = new UploadManager(c);
            return uploadManager;
        }
    }

    public static void deleteObjectList(List<String> keyList){
        LOG.info("keyList: " + keyList);
        List<String> urls = new ArrayList<>();
        Auth auth = Auth.create(UploadConfig.getAccessKey(), UploadConfig.getSecretKey());
        Configuration config = new Configuration(Zone.autoZone());
        BucketManager bucketMgr = new BucketManager(auth, config);
        String bucketName = UploadConfig.getBucket();
        for(String key: keyList) {
            try {
                Response res = bucketMgr.delete(bucketName, key);
                LOG.info("res: " + res.bodyString());
                urls.add(UploadConfig.getOldUrl() + key);
            } catch (QiniuException e) {
                LOG.info("e: " + e.getMessage());
                e.printStackTrace();
            }
        }
        CdnManager c = new CdnManager(auth);
        try {
            LOG.info("keyList: " + urls);
            c.refreshUrls(urls.toArray(new String[urls.size()]));
        } catch (QiniuException e) {
            LOG.info("e: " + e.getMessage());
            e.printStackTrace();
        }
    }


}
